package com.framework.localization
{
    import mx.resources.IResourceBundle;

	/**
	 * 
	 * Provides a set of methods regarding localizing components
	 * 
	 */
	 	
	public final class LocalizationHelper
	{
 		private static var DELIMITER:String = ".";
 
 		/**
		 * 
		 * Method to localize an object given a resource bundle. 
		 * Key names of resource bundle must match property names of 
		 * object in order for the object to be localized. 
		 * 
		 * <p>
		 * Below is an example which demonstrates how to implement localization
		 * of an object (typically a UIComponent), given a ResourceBundle containing:
		 * 
		 * test.text=Hello
		 * test2.text=Goodbye
		 *  
		 * </p>
		 * 
		 * @example
		 * <listing verison="3.0">
	 	 * import com.weightwatchers.framework.localization.LocalizationHelper;
		 * 
		 * [ResourceBundle("myResources")]
		 * private var resources:ResourceBundle;
		 * 
		 * LocalizationHelper.localizeMe(this, resources);
		 * 
		 *
		 * <mx:Label id="test" text="test" y="100"/>
		 * <mx:Text id="test2" text="test2" y="120"/>
		 * 
 		 * </listing>
		 * 
		 * @param 	an object whose members are to be localized
		 * @param	reference to a resource bundle from which to populate members of obj
		 * @throws  
		 */		
       public static function localize(obj:Object, resources:IResourceBundle):void
        {
        	var resName:String;
        	var resValue:String;
        	var resourceNameArray:Array;
        	
         	for (resName in resources.content)
        	{
        		resValue = resources.content[resName];
        		resourceNameArray = resName.split(LocalizationHelper.DELIMITER);
        		setResource(resourceNameArray, obj, resValue)		
        	}
        }
        
  		/**
		 * 
		 * Private helper function to set the value of an object given a potentially
		 * nested property respresented as an array
		 * 
		 * @param	an array representing a nested property that is typically expressed
		 * 			via dot notation (i.e., test.text would be represented as a array with
		 * 			2 elements test and text)
		 * @param	the parent object containing the property
		 * @param	the value to assign to the property
		 * 
		 */
		private static function setResource(nameArray:Array, obj:Object, val:String):void
		{
			if (nameArray!= null && obj!=null && val!=null)
			{
				var shifted:String = String(nameArray.shift());
	
				if (nameArray.length > 0)
				{
					setResource(nameArray, obj[shifted], val);
				}
				else
				{
					if(obj.hasOwnProperty(shifted))
					{
						obj[shifted] = val;
					}
				}
			}
		}
	}
}